import axios from 'axios';
import { Message } from 'element-ui';
import { getToken, removeToken } from '@/utils/auth';
import { Loading } from 'element-ui';
import router from '../router';
let loadingInstance;
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (getToken()) {
      config.headers['token'] = getToken();
    } else {
      config.headers['token'] = -1;
    }
    if (config.url.indexOf('http') !== -1) {
      config.baseURL = '';
    }
    // 是否显示loading
    if (!config.disableLoading) {
      loadingInstance = Loading.service({
        text: '正在努力加载中...',
        customClass: 'loading-custom',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      });
    }
    return config;
  },
  error => {
    // do something with request error
    loadingInstance && loadingInstance.close();
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    loadingInstance && loadingInstance.close();
    // 第三方库
    if (response.data.code && (response.data.code === '200' || response.data.code === '0' || response.data.code === '506')) {
      return Promise.resolve(response.data);
    } else if (response.data.code === '401' || response.data.code === '403') {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 3000
      });
      removeToken(); // 删除已经失效或过期的token（不删除也可以，因为登录后覆盖）
      router.push({ path: '/login ' });
      return Promise.reject();
    } else if (response.data.code !== '200' || response.data.code !== '401' || response.data.code === '403') {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 3000
      });
      return Promise.reject();
    } else {
      return Promise.resolve(response.data);
    }
  },
  error => {
    loadingInstance && loadingInstance.close();
    Message({
      message: error.message,
      type: 'error',
      duration: 3000
    });
    return Promise.reject();
  }
);

export default service
